using DiLu.Expansion.File.Operates.FTP.Configs;

namespace DiLu.Expansion.File.Operates.FTP;

/// <summary>
///     保存文件到FTP
/// </summary>
public static class SaveFtpFile
{
    /// <summary>
    ///     保存文件流到FTP
    /// </summary>
    /// <param name="config">文件流保存到FTP配置</param>
    /// <returns></returns>
    public static async Task<string> SaveAsync(this SaveFileStreamToFtpConfig config)
    {
        if (!config.FtpClient.IsConnected) await config.FtpClient.AutoConnect();
        //文件完整路径
        string fileFullPath;
        //文件相对路径
        string fileRelativePath;
        do
        {
            //保存时间
            var nowTime = DateTime.Now;
            //新文件名称
            var newFileName = $"{nowTime:yyyyMMddHHmmssfffff}{config.FileExtension}";
            //相对目录
            var relativeDirectory = Path.Combine($"{nowTime:yyyy}", $"{nowTime:MM}", $"{nowTime:dd}");
            //完整目录
            var fullDirectory = Path.Combine(config.RootDirectory, config.FileGroupName, relativeDirectory);
            //如果不存在创建文件夹
            if (!await config.FtpClient.DirectoryExists(fullDirectory))
                await config.FtpClient.CreateDirectory(fullDirectory);
            fileFullPath = Path.Combine(fullDirectory, newFileName);
            fileRelativePath = Path.Combine(relativeDirectory, newFileName);
            await Task.Delay(0);
        }
        //如果文件夹下文件名称存在，则重新生成文件名称
        while (await config.FtpClient.FileExists(fileFullPath));

        await config.FtpClient.UploadStream(config.FileStream, fileFullPath);

        //不自动关闭客户端直接返回
        if (!config.AutoCloseFtpClient) return fileRelativePath;
        await config.FtpClient.CloseFtpClientConnectAsync();
        return fileRelativePath;
    }
}